var time = 2000
var Golbal = {
    //用户名
    UserName:"",
    //角色Id
    Role:'',
    //学校Id
    SchoolId:'',
    //用户ID
    UserId:'',
    //用于退出登录
    ExitLoadingBooelan:false,
    StateDate:'',
}
//时间转换

function renderTime(date) {
    var dateee = new Date(date).toJSON();
    var A = new Date(+new Date(dateee) + 8 * 3600 * 1000).toISOString().replace(/T/g, ' ').replace(/\.[\d]{3}Z/, '')
    return A
}
function renderTimes(date) {
    var dateee = new Date(date).toJSON();
    var A = new Date(+new Date(dateee) + 8 * 3600 * 1000).toISOString().replace(/T/g, ' ').replace(/\.[\d]{3}Z/, '')
    if(A==="1970-01-01 08:00:00"){
        A="未提交成绩"
    }
    return A
}
//获取token数据
function postDataplain(url, data) {
    return fetch(process.env.VUE_APP_URL + url, {
        body: data,
        headers: {
            "content-type": "text/plain"
        },
        method: 'POST',
    })
        .then(response => {
            if (response.status === 200) {
                return response.json();
            } else {
                thrownewError("服务器无法连接");
            }
        })
}
//不带token
function postDatajson(url, data) {
    return fetch(process.env.VUE_APP_URL + url, {
        body: data,
        headers: {
            "content-type": "application/json",
        },
        method: 'POST',
    })
        .then(response => {
            if (response.status === 200) {
                return response.json();
            } else if (response.status === 404) {
                return response.status
            } else if (response.status === 500) {
                return response.status
            }
        })
}

function ThirdPartyDataSubmit(url, data) {
    return fetch( url, {
        headers: { 'Content-Type': 'application/x-www-form-urlencoded'},
        changeOrigin: true,
        method: 'POST',
        body: data

    })
        .then(response => {
            if (response.status === 200) {
                return response.json();
            } else if (response.status === 404) {
                return response.status
            } else if (response.status === 500) {
                return response.status
            }
        })
}

//带token
function postData(url, data, token) {
    var tokens = "Bearer " + token
    return fetch(process.env.VUE_APP_URL + url, {
        body: data,
        headers: {
            "content-type": "application/json",
            "Authorization": tokens
        },
        method: 'POST',
    })
        .then(response => {
            if (response.status === 200) {
                return response.json();
            } else {
                thrownewError("服务器无法连接");
            }
        }).catch((error)=>{
            console.log('接口断开连接',error);
            
        })
}
//登录token
function Loading() {
    postDatajson("/api/TokenAuth/Authenticate", JSON.stringify({ userNameOrEmailAddress: "admin", password: "123qwe", rememberClient: true }))
    .then(function (response) {
        sessionStorage.setItem("token", response.result.accessToken)
    })
    .catch((error) => {

    });
}
//登录
    function Loadings(selfs,router) {
    let self = selfs;
    postDatajson(
        "/api/TokenAuth/Authenticate",
        JSON.stringify({
            userNameOrEmailAddress: self.UserName,
            password: self.PassWord,
            rememberClient: true,
            TenantName: "default",
        })
    ).then(function (response) {
        
        if(response.result.success){
           sessionStorage.setItem("token", response.result.result.accessToken);
           postData("/api/User/GetByUserName", JSON.stringify({"UserName": self.UserName }), response.result.result.accessToken).
           then(function (user) {
            postData("/api/SchoolManage/GetById", JSON.stringify({"id": user.result.result.schoolId }), response.result.result.accessToken).
            then(function (rep) {
            Golbal.UserName = user.result.result.name
            Golbal.Role = user.result.result.role
            Golbal.SchoolId = user.result.result.schoolId
            Golbal.UserId = user.result.result.id
            sessionStorage.setItem("userid", user.result.result.id)
            //角色
            sessionStorage.setItem("role", user.result.result.role)
            //学校ID
            sessionStorage.setItem("schoolId", user.result.result.schoolId)
            //用户名ID
            sessionStorage.setItem("UserName", user.result.result.name)
            //性别
            sessionStorage.setItem("Surname", user.result.result.Surname)
            sessionStorage.setItem("wiretapping", "1")
            sessionStorage.setItem("StateDate", "false")
            self.SchoolImageId = "https://mix-statics.oss-cn-shanghai.aliyuncs.com/Platform/Icons/Schools/"+user.result.result.schoolId+".png"
            ProducSetLocalStorageLoad(self,user.result.result.schoolId,rep.result.result.name)
            self.LoadingWaitPanelBoolean=true
            self.LoadTimer = setTimeout(function () {
                self.LoadingStateValue = "登录成功"
                if(user.result.result.role===3){
                    router.push({
                        name: 'Match',
                    });
                }else if(user.result.result.role===4){
                    router.push({
                        name: 'Match',
                    });
                }else{
                    router.push({ 
                        name: 'HomePage',
                    });
                }
                clearTimeout(self.LoadTimer)
                self.LoadTimer = null
                Golbal.ExitLoadingBooelan=false
            }, 1500);
            }).catch(error => {
                self.Error = "请联系服务商处理"
            });
            
        }).catch(error => {
            self.Error = "请联系服务商处理"
        });
        }
        else{
            if(response.result.error==="请输入正确的密码！"){
                self.Error = "请输入正确的密码"
            }
            if(response.result.error==="请输入正确的用户名！"){
                self.Error = "请输入正确的用户名"
            }
            if(response.result.error==="登录过于频繁，请稍后再登录！"){
                self.Error = "登录过于频繁，请稍后再登录"
            }
        }
    }).catch((error) => {
        self.Error = "帐号密码错误"
    });

}
async function ProducSetLocalStorageLoad(User,schoolId,schoolname){
    let checState = "";
    if (User.checkList.length === 1) {
      checState = User.checkList[0];
    }
    if (User.checkList.length === 2) {
      checState = User.checkList[0] + "," + User.checkList[1];
    }
    let LoadingValue ={
      UserName:User.UserName,
      PassWord:User.PassWord,
      checState:checState,
      SchoolImageId:schoolId,
      SchoolName:schoolname,
    }
    let rep = await Application.PostMessageAsync(
      Opcode.LocalStorageSaveRequest,
      { Key: 'HengHongLoading', Value: JSON.stringify(LoadingValue)}
    );
    if (rep.Success) {
    //   console.log(rep);
    }
  }
//获取教师所有班级
//创建班级(通过字符串)
function CreateClass(selfs) {

}
//表单验证
function isClass(rule, value, callback) {
    if (!value) {
        return callback(new Error('输入不可以为空'));
    }
    var pattern = /^[\u4e00-\u9fa5a-zA-Z-z0-9]+$/im
    if (pattern.test(value)) {
        return callback()
    }
    return callback(new Error('只能输入数字,汉字,字母'))
}
function isTimeClass(rule, value, callback) {
    let times = /^(\d{4})(-)(\d{2})$/
    if (times.test(value)) {
        return callback();
    }
    return callback(new Error('请输入正确的时间格式:XXXX(年)-XX(月)'))
}
function Identity(rule, value, callback) {
    let identity = /^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$|^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9]|X)$/
    if (identity.test(value)) {
        return callback();
    }
    return callback(new Error('请输入正确的身份证号'))
}
function NumberVerification(rule, value, callback) {
    let number = /^\d+$|^\d+[.]?\d+$/
    if (number.test(value)) {
        return callback();
    }
    return callback(new Error('只能输入数字'))
}
function CharacterVerification(rule, value, callback) {
    let Character = /[^\u4E00-\u9FA5]/g
    if (!Character.test(value)) {
        return callback();
    }
    return callback(new Error('只能输入汉字'))
}
function IponeVerification(rule, value, callback) {
    let Ipone = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/
    if (Ipone.test(value)) {
        return callback();
    }
    return callback(new Error('请输入正确的手机号'))
}


//转换时间1
function TimeChange(number) {
    var integers = parseInt(number / 60)
    var yu = number % 60
    var strings = ''
    if (integers == 0) {
        strings = yu + "秒"
    } else {
        strings = integers + "分" + yu + "秒"
    }
    return strings
}
function TimeChangeTwo(number) {
    var fen = parseInt(number / 60)
    var miao = number % 60
    var shi = 0
    var yufen = 0
    if (fen > 60) {
        shi = parseInt(fen / 60)
        if (shi < 10) {
            shi = "0" + shi
        }
    }
    yufen = fen % 60
    if (yufen < 10) {
        yufen = "0" + yufen
    }
    if (miao < 10) {
        miao = "0" + miao
    }
    return shi + ":" + yufen + ":" + miao
}
//设置cookie
function setCookie(c_name, c_pwd, exdays, checked) {
    var exdate = new Date(); //获取时间
    exdate.setTime(exdate.getTime() + 24 * 60 * 60 * 1000 * exdays); //保存的天数
    //字符串拼接cookie
    window.document.cookie = "userName" + "=" + c_name + ";path=/;expires=" + exdate.toGMTString();
    window.document.cookie = "userPwd" + "=" + c_pwd + ";path=/;expires=" + exdate.toGMTString();
}
//读取cookie
function getCookie() {
    let arrs = []
    if (document.cookie.length > 0) {
        var arr = document.cookie.split('; ');
        for (var i = 0; i < arr.length; i++) {
            if (arr[i].split('=')[0] === 'userName') {
                arrs.push(arr[i].split('=')[1])
            }
            if (arr[i].split('=')[0] === 'userPwd') {
                arrs.push(arr[i].split('=')[1])
            }
        }
    }
    return arrs
}
//清除cookie
function clearCookie() {
    setCookie("", "", -1); //修改2值都为空，天数为负1天就好了
}
//计算两个时间只差
// TimeDifference ('2020-09-10 17:10:29','2020-9-18 17:11:35');
function TimeDifference(time1, time2) {
    //定义两个变量time1,time2分别保存开始和结束时间
    var stime = new Date(time1).getTime();
    var etime = new Date(time2).getTime();
    var usedTime = (etime - stime) / 1000;  //两个时间戳相差的毫秒数
    // var days=Math.floor(usedTime/(24*3600*1000));
    //              //计算出小时数
    // var leave1=usedTime%(24*3600*1000);    //计算天数后剩余的毫秒数
    // var hours=Math.floor(leave1/(3600*1000));
    //              //计算相差分钟数
    // var leave2=leave1%(3600*1000);        //计算小时数后剩余的毫秒数
    // var minutes=Math.floor(leave2/(60*1000));
    // var time = days + "天"+hours+"时"+minutes+"分";
    //var time = days;
    return TimeChange(usedTime)
}
//new Date转化成时间格式
function dateToFormat(value) {
    const dateTme = new Date(value)
    const Y = dateTme.getFullYear()
    const M = dateTme.getMonth() + 1 < 10 ? "0" + (dateTme.getMonth() + 1) : dateTme.getMonth() + 1
    const D = dateTme.getDate() < 10 ? "0" + dateTme.getDate() : dateTme.getDate()
    const h = dateTme.getHours() < 10 ? "0" + dateTme.getHours() : dateTme.getHours()
    const m = dateTme.getMinutes() < 10 ? "0" + dateTme.getMinutes() : dateTme.getMinutes()
    const s = dateTme.getSeconds() < 10 ? "0" + dateTme.getSeconds() : dateTme.getSeconds()
    return Y + "-" + M + "-" + D + " " + h + ":" + m + ":" + s
}
//转换时分秒
function SecondToTime(seconds){
    let hour = parseInt(seconds/3600);
    let h = hour<10?"0"+hour:""+hour;
    let minute = parseInt((seconds%3600)/60);
    let m = minute<10?"0"+minute:""+minute;
    let second = parseInt(seconds%60);
    let s = second<10?"0"+second:""+second;
    return h+":"+m+":"+s;
}
function fortime(time1, time2) {
    var t1 = dateFormats(time1)
    var t2 = dateToFormat(time2)
    var stime = new Date(t1).getTime();
    var etime = new Date(t2).getTime();
    var usedTime = (etime - stime) / 1000;
    return usedTime
}
function dateFormats(dataStr) {
    var dateee = new Date(dataStr).toJSON();
    return new Date(+new Date(dateee) + 8 * 3600 * 1000).toISOString().replace(/T/g, ' ').replace(/\.[\d]{3}Z/, '')
}
function deepClone(source) {
    const targetObj = source.constructor === Array ? [] : {}; // 判断复制的目标是数组还是对象
    for (const keys in source) { // 遍历目标
        if (source.hasOwnProperty(keys)) {
            if (source[keys] && typeof source[keys] === 'object') { // 如果值是对象，就递归一下
                targetObj[keys] = source[keys].constructor === Array ? [] : {};
                targetObj[keys] = deepClone(source[keys]);
            } else { // 如果不是，就直接赋值
                targetObj[keys] = source[keys];
            }
        }
    }
    return targetObj;
}
function ObjectToString(Arr) {
    let obj = {}
    for (let item in Arr) {
        obj[Arr[item].name] = Arr[item].value;
    };
    return obj
}
function numFilter(value){
    let realVal = '';
    if (!isNaN(value) && value !== '') {
        let tempVal = parseFloat(value).toFixed(3);
        realVal = tempVal.substring(0, tempVal.length - 1);
    }else {
        realVal = '–';
        }
    return realVal;
}
function DownloadDisplay(arr, self) {
    if (arr.length === 2) {
        self.ProductActivationListArr[self.DownloadProductInformationArr[1].ProductIndex].State = 12
    }
    if (arr.length === 3) {
        for (let i = 1; i < 3; i++) {
            self.ProductActivationListArr[self.DownloadProductInformationArr[i].ProductIndex].State = 12
        }
    }
    if (arr.length === 4) {
        for (let i = 1; i < 4; i++) {
            self.ProductActivationListArr[self.DownloadProductInformationArr[i].ProductIndex].State = 12
        }
    }
    if (arr.length === 5) {
        for (let i = 1; i < 5; i++) {
            self.ProductActivationListArr[self.DownloadProductInformationArr[i].ProductIndex].State = 12
        }
    }
    if (arr.length === 6) {
        for (let i = 1; i < 6; i++) {
            self.ProductActivationListArr[self.DownloadProductInformationArr[i].ProductIndex].State = 12
        }
    }
    if (arr.length === 7) {
        for (let i = 1; i < 7; i++) {
            self.ProductActivationListArr[self.DownloadProductInformationArr[i].ProductIndex].State = 12
        }
    }
    if (arr.length === 8) {
        for (let i = 1; i < 8; i++) {
            self.ProductActivationListArr[self.DownloadProductInformationArr[i].ProductIndex].State = 12
        }
    }
    if (arr.length === 9) {
        for (let i = 1; i < 9; i++) {
            self.ProductActivationListArr[self.DownloadProductInformationArr[i].ProductIndex].State = 12
        }
    }
    if (arr.length === 10) {
        for (let i = 1; i < 10; i++) {
            self.ProductActivationListArr[self.DownloadProductInformationArr[i].ProductIndex].State = 12
        }
    }
    if (arr.length === 11) {
        for (let i = 1; i < 11; i++) {
            self.ProductActivationListArr[self.DownloadProductInformationArr[i].ProductIndex].State = 12
        }
    }
    if (arr.length === 12) {
        for (let i = 1; i < 12; i++) {
            self.ProductActivationListArr[self.DownloadProductInformationArr[i].ProductIndex].State = 12
        }
    }
    if (arr.length === 13) {
        for (let i = 1; i < 13; i++) {
            self.ProductActivationListArr[self.DownloadProductInformationArr[i].ProductIndex].State = 12
        }
    }
    if (arr.length === 14) {
        for (let i = 1; i < 14; i++) {
            self.ProductActivationListArr[self.DownloadProductInformationArr[i].ProductIndex].State = 12
        }
    }
    if (arr.length === 15) {
        for (let i = 1; i < 15; i++) {
            self.ProductActivationListArr[self.DownloadProductInformationArr[i].ProductIndex].State = 12
        }
    }
    if (arr.length === 16) {
        for (let i = 1; i < 16; i++) {
            self.ProductActivationListArr[self.DownloadProductInformationArr[i].ProductIndex].State = 12
        }
    }
    if (arr.length === 17) {
        for (let i = 1; i < 17; i++) {
            self.ProductActivationListArr[self.DownloadProductInformationArr[i].ProductIndex].State = 12
        }
    }
    if (arr.length === 18) {
        for (let i = 1; i < 18; i++) {
            self.ProductActivationListArr[self.DownloadProductInformationArr[i].ProductIndex].State = 12
        }
    }
}
function bubbleSort(arr) {
    let len = arr.length;
    for (let i = 0; i < len; i++) {
        for (let j = 0; j < len - 1 - i; j++) {
            if (arr[j].sort > arr[j + 1].sort) {        //相邻元素两两对比
                let temp = arr[j + 1];        //元素交换
                arr[j + 1] = arr[j];
                arr[j] = temp;
            }
        }
    }
    return arr;
}


export {
    Golbal,
    time,
    bubbleSort,
    DownloadDisplay,
    postDataplain,
    postDatajson,
    ThirdPartyDataSubmit,
    postData,
    Loadings,
    CreateClass,
    renderTime,
    renderTimes,
    isClass,
    TimeChange,
    setCookie,
    getCookie,
    clearCookie,
    TimeDifference,
    TimeChangeTwo,
    dateToFormat,
    fortime,
    deepClone,
    ObjectToString,
    isTimeClass,
    Identity,
    NumberVerification,
    CharacterVerification,
    IponeVerification,
    SecondToTime,
    dateFormats,
    numFilter
}